﻿namespace AjLogo.Primitives
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using AjLogo.Language;

    public class CallProcedure : IExpression
    {
        private IProcedure procedure;
        private ICollection<IExpression> parameters;

        public CallProcedure(IProcedure procedure, ICollection<IExpression> parameters)
        {
            if (procedure == null)
                throw new System.ArgumentNullException("procedure");

            if (parameters == null)
                throw new System.ArgumentNullException("parameters");

            this.procedure = procedure;
            this.parameters = parameters;
        }

        public object Evaluate(BindingEnvironment environment)
        {
            if (this.procedure.Arity == 0)
                return this.procedure.Evaluate(environment);

            object[] values = new object[this.parameters.Count];

            int k = 0;

            foreach (IExpression parameter in this.parameters)
                values[k++] = parameter.Evaluate(environment);

            return this.procedure.Evaluate(environment, values);

            // TODO Remove
/*
            switch (this.procedure.Arity)
            {
                case 1:
                    return this.procedure.Evaluate(environment, values[0]);
                case 2:
                    return this.procedure.Evaluate(environment, values[0], values[1]);
                case 3:
                    return this.procedure.Evaluate(environment, values[0], values[1], values[2]);
                default:
                    return this.procedure.Evaluate(environment, values);
            }

            Procedure proc = (Procedure)this.procedure;
            Environment newenv = new Environment(environment);

            for (k = 0; k < proc.Arity; k++)
                newenv.SetValue(proc.ParameterNames[k], values[k]);

            return proc.Expression.Evaluate(newenv);
 */
        }
    }
}
